const sequelize = require("../sequelize_ins");
const { DataTypes } = require("sequelize");
const { SERVER_HOST, DOCTOR_VALID_STATUS } = require("../../sys_config");

const define_filed_watcher = (filed_name, type = DataTypes.STRING) => ({
  type,
  get() {
    const val = this.getDataValue(filed_name);
    return val ? `${SERVER_HOST}/${val}` : "";
  },
  set(val) {
    this.setDataValue(filed_name, val);
  },
});

const core = sequelize.define("doctor_info", {
  u_id: DataTypes.INTEGER,
  avatar: define_filed_watcher("avatar"),
  pb_date_id: DataTypes.INTEGER,
  pb_time_id: DataTypes.INTEGER,
  department_id: DataTypes.INTEGER,
  disease_id: DataTypes.INTEGER,
  doc: define_filed_watcher("doc"),
  license: define_filed_watcher("license"),
  valid: { type: DataTypes.INTEGER, defaultValue: DOCTOR_VALID_STATUS.UNVALID },
  enable: { type: DataTypes.BOOLEAN, defaultValue: true },
});

module.exports = {
  core,

  async get_doctors(query) {
    const data = await this.core.findAll({
      where: query,
      include: ["user", "pb_date", "pb_time", "department", "disease"],
    });
    return data.map((raw) => ({
      id: raw.id,
      d_id: raw.u_id,
      avatar: raw.avatar,
      doc: raw.doc,
      license: raw.license,
      enable: raw.enable,
      name: raw.user.name,
      phone: raw.user.phone,
      pb_date: raw.pb_date?.type,
      pb_time: raw.pb_time?.type,
      department: raw.department?.name,
      disease: raw.disease?.name,
      valid: raw.valid,
    }));
  },
};
